/*
*  功能：根据roles产生routes
 */

import {constRouters, asyncRouters} from "@/router";

const GENERATE_ROUTES = 'GENERATE_ROUTES'

function hasPermission(roles, router) {
  return roles.some(role=>{
    return router.meta === undefined || router.meta.roles === undefined || router.meta.roles.indexOf(role) > -1;
  })
}

function filterRouteMap(routers, roles) {
  return routers.filter(router=>{
    if(hasPermission(roles, router)){
      if(router.children && router.children.length){
        router.children = filterRouteMap(router.children, roles)
      }
      return true
    }
    return false
  })
}

//定义state
const state = {
  permissions: {
    addRoutes:        [], //调用router.addRoutes时使用的路由
    permissionRoutes: constRouters  //进行权限处理后的所有路由
  }
}

//定义getters -- 相当于Store的计算属性
const getters = {
  permissionRoutes: function (state, getters) {
    return state.permissions.permissionRoutes
  },
  addRoutes: function (state, getters) {
    return state.permissions.addRoutes
  }
}

//Mutations
//作用：同步调用 store.commit 方法，更改 Vuex 的 store 中的状态的唯一方法
const mutations = {
  [GENERATE_ROUTES]: function (state, roles) {
    state.permissions.addRoutes = roles.indexOf('ROLE_ADMIN') > -1 ? asyncRouters : filterRouteMap(asyncRouters, roles)
    state.permissions.permissionRoutes = constRouters.concat(state.permissions.addRoutes)
  }
}

//Actions
//作用：1.提交的是 mutation，而不是直接变更状态
//     2.可以包含任意异步操作
const actions = {
  generateRoutes: function ({commit}, roles) {
    return new Promise((resolve, reject)=>{
      commit(GENERATE_ROUTES, roles)
      resolve()
    })
  }
}

export default {
  state,
  getters,
  mutations,
  actions
}
